﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// 背包
/// </summary>
public class Knapsack : ShowHideBehaviour {

    public KnapsackSlot KnapsackSlotPrefab;

    private ScrollRect ScrollRect;
    private RectTransform ContentTransform;
    private List<KnapsackSlot> KnapsackSlots;
    private SimpleShowHideComponent ShowHideScrollbar;
    private GameObject CloseImage;
    private float Smoothing = 10;
    private const int MinKnapsackSlotCount = 70;

    // Use this for initialization
    void Start () {
        base.InitShowHide();
        this.ScrollRect = this.transform.Find("Box").GetComponent<ScrollRect>();
        this.ShowHideScrollbar = this.ScrollRect.transform.Find("Scrollbar").GetComponent<SimpleShowHideComponent>();
        this.ContentTransform = this.ScrollRect.transform.Find("Content").GetComponent<RectTransform>();
        this.KnapsackSlots = new List<KnapsackSlot>(this.ContentTransform.GetComponentsInChildren<KnapsackSlot>());
        this.InitArticles();
        this.ResizeContent();
    }
	
	// Update is called once per frame
	void Update () {
        base.HandleShowHide(Smoothing);
    }

    /// <summary>
    /// 顺序查找一个空格子
    /// </summary>
    /// <returns></returns>
    public KnapsackSlot GetEmptySlot() {
        foreach (KnapsackSlot knapsackSlot in this.KnapsackSlots) {
            if (knapsackSlot.IsEmpty()) { // 空格子
                return knapsackSlot;
            }
        }
        return this.NewKnapsackSlot();
    }

    /// <summary>
    /// 顺序获得一个不满的格子
    /// </summary>
    /// <param name="article"></param>
    /// <returns></returns>
    public KnapsackSlot GetNotFullSlot(Article article) {
        int spaceNum = article.ArticleTemplet.SpaceNum;
        if (spaceNum == 1) { // 容量为1
            return this.GetEmptySlot();
        }
        // 其下为容量大于1
        foreach (KnapsackSlot knapsackSlot in this.KnapsackSlots) {
            if (knapsackSlot.IsEmpty()) { // 空格子
                return knapsackSlot;
            }
            // 其下为非空格子
            ArticleItem articleItem = knapsackSlot.ArticleItem;
            if (!knapsackSlot.IsFull && articleItem.ArticleInfo.Article.ArticleTempletId.Equals(article.ArticleTempletId)) { // 容量未满并且id相同
                return knapsackSlot;
            }
        }
        return this.NewKnapsackSlot();
    }

    /// <summary>
    /// 创建一个新的格子，并加入集合
    /// </summary>
    /// <returns></returns>
    public KnapsackSlot NewKnapsackSlot() {
        KnapsackSlot knapsackSlot = Instantiate<KnapsackSlot>(this.KnapsackSlotPrefab);
        knapsackSlot.transform.SetParent(this.ContentTransform, false);
        this.KnapsackSlots.Add(knapsackSlot);
        //this.ScrollRect.verticalNormalizedPosition = 0;
        this.SynchronizeArticleInfo(); // 同步背包数据
        if (this.KnapsackSlots.Count > Knapsack.MinKnapsackSlotCount) {
            this.ShowHideScrollbar.Show();
        }
        this.ResizeContent();
        return knapsackSlot;
    }

    /// <summary>
    /// 删除一个背包格子
    /// </summary>
    /// <param name="knapsackSlot"></param>
    public void RemoveKnapsackSlot(KnapsackSlot knapsackSlot) {
        Personage personage = GlobalData.Instance.GetPlayerPersonage();
        personage.KnapsackArticles.Remove(knapsackSlot.ArticleInfo); // 删除背包对应数据
        Destroy(knapsackSlot.gameObject);
        this.KnapsackSlots.Remove(knapsackSlot);
        if (this.KnapsackSlots.Count <= Knapsack.MinKnapsackSlotCount) {
            this.ShowHideScrollbar.Hide();
        }
        print(this.KnapsackSlots.Count);
        this.ResizeContent();
    }

    /// <summary>
    /// 丢弃物品
    /// 如果之前的格子是装备格子，则脱下装备，之前的格子置空
    /// 如果格子数量大于基本格子数，则删除掉格子
    /// 如果格子数不大于基本格子数，则清空格子
    /// </summary>
    /// <param name="knapsackSlot">之前的格子</param>
    public void DiscardArticle(KnapsackSlot knapsackSlot) {
        ArticleManager articleManager = ArticleManager.Instance;
        if (knapsackSlot.ArticleCategory != Constant.ArticleCategory.Anything) { // 是装备格子
            if (knapsackSlot.ArticleCategory != Constant.ArticleCategory.Anything) { // 之前的格子是装备格子
                articleManager.UpdatePersonageProp(knapsackSlot.ArticleInfo.Article, null); // 脱下装备
                knapsackSlot.ClearArticle();
            }
            //print("1");
        } else if (this.KnapsackSlots.Count > Knapsack.MinKnapsackSlotCount) { // 大于Knapsack.MinKnapsackSlotCount或者是装备槽，则清空格子
            this.RemoveKnapsackSlot(knapsackSlot);
            //print("2");
        } else { // 不大于时，则清空格子
            knapsackSlot.ClearArticle();
            //print("3");
        }
    }

    /// <summary>
    /// 修改content大小
    /// </summary>
    private void ResizeContent() {
        float width = this.ContentTransform.sizeDelta.x;
        float height = this.ContentTransform.sizeDelta.y;
        float h;
        if (this.KnapsackSlots.Count > Knapsack.MinKnapsackSlotCount) {
            h = this.KnapsackSlots.Count / 10 * 100 + 90;
        } else {
            h = 690;
        }
        if (height != h) {
            this.ContentTransform.sizeDelta = new Vector2(width, h);
        }
    }

    /// <summary>
    /// 初始化背包，使背包与背包数据一致
    /// </summary>
    private void InitArticles() {
        Personage personage = GlobalData.Instance.GetPlayerPersonage();
        List<ArticleInfo> articleInfos = personage.KnapsackArticles;
        int num = articleInfos.Count - this.KnapsackSlots.Count;
        if (num > 0) { // 如果人物的背包物品信息数大于了背包物品槽，则先补全
            for (int i = 0; i < num; i++) {
                this.NewKnapsackSlot();
            }
        } else { // 物品槽多了
            for (int i = this.KnapsackSlots.Count - 1; i >= this.KnapsackSlots.Count + num; i--) {
                this.RemoveKnapsackSlot(this.KnapsackSlots[i]);
            }
        }
        // 如此，便保持了一致
        for (int i = 0; i < articleInfos.Count; i++) {
            ArticleInfo articleInfo = articleInfos[i];
            KnapsackSlot knapsackSlot = this.KnapsackSlots[i];
            knapsackSlot.ArticleInfo = articleInfo;
            if (articleInfo.Article != null) {
                knapsackSlot.StoreArticle(articleInfo);
            }
        }
    }

    /// <summary>
    /// 同步背包数据
    /// </summary>
    private void SynchronizeArticleInfo() {
        Personage personage = GlobalData.Instance.GetPlayerPersonage();
        if (this.KnapsackSlots.Count <= personage.KnapsackArticles.Count) { // 如果ui数量不多于于数据数量，则直接绑定上数据
            int index = this.KnapsackSlots.Count - 1; // 新增的物品槽的序数
            this.KnapsackSlots[index].ArticleInfo = personage.KnapsackArticles[index];
        } else { // 如果ui数量超过数据数量，则先添加数据，再绑定
            ArticleInfo articleInfo = new ArticleInfo();
            personage.KnapsackArticles.Add(articleInfo);
            int index = personage.KnapsackArticles.Count - 1; // 新增的数据的序数
            this.KnapsackSlots[index].ArticleInfo = articleInfo;
            if (this.KnapsackSlots.Count > personage.KnapsackArticles.Count) {
                this.SynchronizeArticleInfo();
            }
        }
    }

    /// <summary>
    /// 背包里是否有这个格子
    /// </summary>
    /// <param name="knapsackSlot"></param>
    /// <returns></returns>
    public bool ContainsKnapsackSlot(KnapsackSlot knapsackSlot) {
        return this.KnapsackSlots.Contains(knapsackSlot);
    }
}
